// pages/student/kechenbiao/detail/detail.js
const app = getApp();

Page({
  data: {
    courseId: null,
    courseInfo: null,
    isLoading: true,
    originalCourseData: null // 保存从课表页面传来的原始数据
  },

  onLoad: function(options) {
    if (options.id) {
      // 尝试获取从课表页面传递的课程数据
      let originalData = null;
      try {
        if (options.data) {
          originalData = JSON.parse(decodeURIComponent(options.data));
          console.log('从课表页面获取的原始数据:', originalData);
        }
      } catch (e) {
        console.error('解析传递的课程数据失败:', e);
      }
      
      this.setData({
        courseId: options.id,
        originalCourseData: originalData
      });
      
      // 如果有原始数据，先显示
      if (originalData) {
        this.setData({
          courseInfo: {
            id: originalData.id,
            name: originalData.name,
            teacher: originalData.teacher,
            location: originalData.location,
            schedule: [{
              day: this.getDayName(originalData.day),
              time: this.getPeriodName(originalData.period),
              location: originalData.location || '未指定地点',
              weeks: `第${originalData.startWeek}-${originalData.endWeek}周`
            }],
            exams: []
          }
        });
      }
      
      // 然后再请求详细数据
      this.fetchCourseDetail();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },
  
  // 获取星期几的名称
  getDayName: function(day) {
    const dayMap = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    return dayMap[(day - 1) % 7] || `未知(${day})`;
  },
  
  // 获取节次的名称
  getPeriodName: function(period) {
    const periodMap = ['1-2节', '3-4节', '5-6节', '7-8节', '9-10节'];
    return periodMap[period] || `第${period+1}节`;
  },
  
  // 获取课程详情
  fetchCourseDetail: function() {
    this.setData({ isLoading: true });
    
    wx.showLoading({
      title: '加载中...',
    });
    
    // 打印调试信息，查看当前的课程ID和原始数据
    console.log('请求课程详情，课程ID:', this.data.courseId);
    console.log('原始课程数据:', this.data.originalCourseData);
    
    // 构建请求参数
    let url = `${app.globalData.serverUrl}/api/courses/${this.data.courseId}?source=timetable`;
    
    // 如果有原始数据，添加原始课程名称作为参数
    if (this.data.originalCourseData && this.data.originalCourseData.name) {
      url += `&name=${encodeURIComponent(this.data.originalCourseData.name)}`;
    }
    
    // 从API获取课程详情
    wx.request({
      url: url,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 200) {
          console.log('获取课程详情成功:', res.data);
          
          // 检查API返回的数据与原始数据是否一致
          if (this.data.originalCourseData && 
              this.data.originalCourseData.name !== res.data.name) {
            console.warn('数据不一致警告: API返回的课程名称与原始数据不同',
              '原始:', this.data.originalCourseData.name,
              'API返回:', res.data.name);
          }
          
          // 如果有原始数据，完全使用原始数据的关键信息，只保留API返回的额外信息
          if (this.data.originalCourseData) {
            const originalData = this.data.originalCourseData;
            
            // 创建合并后的课程信息，但完全使用原始数据中的关键信息
            const mergedCourseInfo = {
              // 先使用API返回的所有数据作为基础
              ...res.data,
              // 然后强制覆盖关键字段，使用原始数据
              id: originalData.id,
              name: originalData.name,
              teacher: originalData.teacher,
              location: originalData.location,
              // 保留API返回的其他信息，如课程代码、学分等
              courseCode: res.data.courseCode || '',
              credit: res.data.credit || 0,
              description: res.data.description || `${originalData.name}课程，由${originalData.teacher}老师授课`,
              // 确保schedule字段存在
              schedule: []
            };
            
            // 添加原始数据中的课程安排
            const originalSchedule = {
              day: this.getDayName(originalData.day),
              time: this.getPeriodName(originalData.period),
              location: originalData.location || '未指定地点',
              weeks: `第${originalData.startWeek}-${originalData.endWeek}周`
            };
            
            // 添加到课程安排中
            mergedCourseInfo.schedule.push(originalSchedule);
            
            // 如果API返回的数据中有课程安排，也添加进来
            if (res.data.schedule && Array.isArray(res.data.schedule)) {
              // 过滤掉与原始数据重复的课程安排
              const additionalSchedules = res.data.schedule.filter(item => {
                return !(item.day === originalSchedule.day && 
                         item.time === originalSchedule.time && 
                         item.location === originalSchedule.location);
              });
              
              // 添加不重复的课程安排
              mergedCourseInfo.schedule = [...mergedCourseInfo.schedule, ...additionalSchedules];
            }
            
            this.setData({
              courseInfo: mergedCourseInfo
            });
          } else {
            // 没有原始数据，直接使用API返回的数据
            this.setData({
              courseInfo: res.data
            });
          }
          
          // 获取额外的课表数据
          this.fetchAdditionalTimetableData();
        } else {
          console.error('获取课程详情失败:', res.data);
          wx.showToast({
            title: res.data.message || '获取课程详情失败',
            icon: 'none'
          });
          
          // 如果有原始数据，至少显示原始数据
          if (!this.data.courseInfo && this.data.originalCourseData) {
            const originalData = this.data.originalCourseData;
            this.setData({
              courseInfo: {
                id: originalData.id,
                name: originalData.name,
                teacher: originalData.teacher,
                location: originalData.location,
                schedule: [{
                  day: this.getDayName(originalData.day),
                  time: this.getPeriodName(originalData.period),
                  location: originalData.location || '未指定地点',
                  weeks: `第${originalData.startWeek}-${originalData.endWeek}周`
                }],
                exams: []
              },
              isLoading: false
            });
          } else {
            this.setData({ isLoading: false });
          }
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('请求失败:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
        
        // 如果有原始数据，至少显示原始数据
        if (!this.data.courseInfo && this.data.originalCourseData) {
          const originalData = this.data.originalCourseData;
          this.setData({
            courseInfo: {
              id: originalData.id,
              name: originalData.name,
              teacher: originalData.teacher,
              location: originalData.location,
              schedule: [{
                day: this.getDayName(originalData.day),
                time: this.getPeriodName(originalData.period),
                location: originalData.location || '未指定地点',
                weeks: `第${originalData.startWeek}-${originalData.endWeek}周`
              }],
              exams: []
            },
            isLoading: false
          });
        } else {
          this.setData({ isLoading: false });
        }
      }
    });
  },
  
  // 获取额外的课表数据
  fetchAdditionalTimetableData: function() {
    // 获取当前周次和学期
    const currentWeek = wx.getStorageSync('currentWeek') || 1;
    const semester = wx.getStorageSync('currentSemester') || '';
    
    console.log('请求额外课表数据，参数:', { 
      courseId: this.data.courseId, 
      week: currentWeek, 
      semester: semester 
    });
    
    wx.request({
      url: `${app.globalData.serverUrl}/api/courses/timetable/student`,
      method: 'GET',
      data: {
        week: currentWeek,
        semester: semester,
        courseId: this.data.courseId
      },
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.timetable) {
          console.log('获取额外课表数据成功:', res.data);
          
          // 过滤出当前课程的课表数据
          const courseSchedule = res.data.timetable.filter(item => 
            item.courseId == this.data.courseId || item.id == this.data.courseId
          );
          
          console.log('过滤后的课表数据:', courseSchedule);
          
          if (courseSchedule.length > 0) {
            // 处理课程安排数据
            const schedule = courseSchedule.map(item => {
              // 将数字转换为星期几
              const dayMap = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
              const day = dayMap[item.day - 1] || `未知(${item.day})`;
              
              // 将数字转换为节次
              const periodMap = ['1-2节', '3-4节', '5-6节', '7-8节', '9-10节'];
              const time = periodMap[item.period] || `未知(${item.period})`;
              
              return {
                day: day,
                time: time,
                location: item.location || '未指定地点',
                weeks: `第${item.startWeek}-${item.endWeek}周`
              };
            });
            
            // 合并课程安排数据
            const updatedCourseInfo = {
              ...this.data.courseInfo,
              schedule: [...(this.data.courseInfo.schedule || []), ...schedule]
            };
            
            // 去重
            const uniqueSchedule = [];
            const seen = new Set();
            
            updatedCourseInfo.schedule.forEach(item => {
              const key = `${item.day}-${item.time}-${item.location}`;
              if (!seen.has(key)) {
                seen.add(key);
                uniqueSchedule.push(item);
              }
            });
            
            updatedCourseInfo.schedule = uniqueSchedule;
            
            // 如果有原始数据，确保课程名称和教师信息与原始数据一致
            if (this.data.originalCourseData) {
              updatedCourseInfo.name = this.data.originalCourseData.name;
              updatedCourseInfo.teacher = this.data.originalCourseData.teacher;
            }
            
            this.setData({
              courseInfo: updatedCourseInfo
            });
          }
          
          // 获取考试信息
          this.fetchExamInfo();
        } else {
          console.log('获取额外课表数据失败或无数据:', res.data);
          // 获取考试信息
          this.fetchExamInfo();
        }
      },
      fail: (err) => {
        console.error('请求额外课表数据失败:', err);
        // 获取考试信息
        this.fetchExamInfo();
      }
    });
  },
  
  // 获取考试信息
  fetchExamInfo: function() {
    // 使用正确的API路径
    let url = `${app.globalData.serverUrl}/api/exams/courses/${this.data.courseId}`;
    
    // 如果课程信息中有映射的课程ID，添加到请求参数中
    if (this.data.courseInfo && this.data.courseInfo.mappedCourseId) {
      url += `?mappedId=${this.data.courseInfo.mappedCourseId}`;
    }
    
    wx.request({
      url: url,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        if (res.statusCode === 200) {
          console.log('获取考试安排成功:', res.data);
          
          // 处理考试数据
          const exams = Array.isArray(res.data) ? res.data : [];
          
          // 更新课程信息
          const updatedCourseInfo = {
            ...this.data.courseInfo,
            exams: exams
          };
          
          this.setData({
            courseInfo: updatedCourseInfo,
            isLoading: false
          });
        } else {
          console.log('获取考试安排失败:', res.data);
          this.setData({ isLoading: false });
        }
      },
      fail: (err) => {
        console.error('请求考试安排失败:', err);
        this.setData({ isLoading: false });
      }
    });
  },

  // 查看考试详情
  viewExamDetail: function(e) {
    const examId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/student/kaoshi/detail?id=${examId}`
    });
  },

  // 返回上一页
  goBack: function() {
    wx.navigateBack();
  }
});